import java.util.concurrent.Semaphore;

/**
 * @Author Stringzhua
 * @Date 2024/11/4 11:33
 * description:
 */
public class DeadLockWithSemaphore {
    private Semaphore semaphoreA = new Semaphore(1);
    private Semaphore semaphoreB = new Semaphore(1);

    public void add() throws InterruptedException {
        semaphoreA.acquire();
        Thread.sleep(1000);
        semaphoreB.acquire();
        try {
            System.out.println("执行add()");
        } finally {
            semaphoreB.release();
            semaphoreA.release();
        }

    }

    public void dec() throws InterruptedException {
        while (semaphoreB.tryAcquire()) {
            Thread.sleep(100);
            if (semaphoreA.tryAcquire()) {
                try {
                    System.out.println("执行dec()");
                    return;
                } finally {
                    semaphoreA.release();
                    semaphoreB.release();
                }
            } else {
                semaphoreA.release();
                semaphoreB.release();
            }
        }
    }
}
